/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * LeaveFeedback.java
 *
 * Created on Sep 28, 2010, 10:51:44 PM
 */

package GUI.other;

import GUI.MainFrame;
import Interfaces.Loadable;
import functions.Dogy;
import functions.HTTPRequest;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.Point;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BoxLayout;
import javax.swing.JEditorPane;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

/**
 *
 * @author JArik
 */
public class LeaveFeedback extends javax.swing.JFrame {

    /** Creates new form LeaveFeedback */
    private MainFrame manager;


    public static final int PLANNED_TAB = 0;
    private static final int DONE_TAB = 1;
    private static final int FEEDBACK_TAB = 2;


    private JPanel tasksPanel;
    // Task Statuses
    public enum TaskStatus
    {
        PLANNED(1,"planned"),
        TESTING(2,"testing"),
        DEVELOPMENT(4,"development"),
        DONE(8,"done");
        
        private int id;
        private String descr;
        TaskStatus(int id, String descr)
        {
            this.id = id;
            this.descr = descr;
        }
        public int getId()
        {
            return id;
        }
        public String toString()
        {
            return id+"";
        }
        public String getDescr()
        {
            return descr;
        }
    }
    private String getTaskDescr(int id)
    {
            if(id == 0)
              return "Неизвестно";
            String res = "";
            for(TaskStatus t : TaskStatus.values())
                if((t.getId() & id) == t.getId())
                {
                    if(!res.isEmpty())
                        res += ", ";
                    res += t.getDescr();
                }

            return res;
    }
    
    public LeaveFeedback()
    {
        initComponents();
        feedbackSendProgress.setVisible(false);
        //feedbackTabsStateChanged(null);
    }

    public LeaveFeedback(MainFrame aThis) 
    {
        initComponents();
        feedbackSendProgress.setVisible(false);
        manager = aThis;
        this.setTitle("Оставить отзыв");
        //feedbackTabsStateChanged(null);
    }

    private HashMap initVars()
    {
        HashMap vars = new HashMap();
        vars.put("version", Dogy.VERSION);
        vars.put("prefix", Dogy.V_PREFIX);
        return vars;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        progressBar = new javax.swing.JProgressBar();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        feedbackField = new javax.swing.JTextArea();
        sendFeedbackButton = new javax.swing.JButton();
        closeButton = new javax.swing.JButton();
        feedbackSendProgress = new javax.swing.JProgressBar();
        jPanel2 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        feedbackTabs = new javax.swing.JTabbedPane();
        plansPane = new javax.swing.JScrollPane();
        donePane = new javax.swing.JScrollPane();
        feedbackPane = new javax.swing.JScrollPane();
        jSeparator1 = new javax.swing.JSeparator();

        progressBar.setFont(new java.awt.Font("Tahoma", 1, 11));
        progressBar.setStringPainted(true);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14));
        jLabel1.setText("Оставьте отзыв\\пожелание");

        feedbackField.setColumns(20);
        feedbackField.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        feedbackField.setRows(5);
        jScrollPane2.setViewportView(feedbackField);

        sendFeedbackButton.setFont(new java.awt.Font("Tahoma", 1, 11));
        sendFeedbackButton.setText("Отправить");
        sendFeedbackButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sendFeedbackButtonActionPerformed(evt);
            }
        });

        closeButton.setFont(new java.awt.Font("Tahoma", 1, 11));
        closeButton.setText("Закрыть");
        closeButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                closeButtonActionPerformed(evt);
            }
        });

        feedbackSendProgress.setString("Посылаю 0%");
        feedbackSendProgress.setStringPainted(true);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 456, Short.MAX_VALUE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 456, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addComponent(closeButton, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(61, 61, 61)
                        .addComponent(feedbackSendProgress, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 49, Short.MAX_VALUE)
                        .addComponent(sendFeedbackButton, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 94, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(sendFeedbackButton, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(closeButton, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(feedbackSendProgress, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 14));
        jLabel2.setText("Что сделано\\запланировано сделать");

        feedbackTabs.setFont(new java.awt.Font("Tahoma", 1, 11));
        feedbackTabs.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                feedbackTabsStateChanged(evt);
            }
        });

        plansPane.setBorder(null);
        plansPane.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        feedbackTabs.addTab("Запланировано", plansPane);

        donePane.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        feedbackTabs.addTab("Сделано", donePane);

        feedbackPane.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        feedbackTabs.addTab("Отзывы", feedbackPane);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(feedbackTabs, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 476, Short.MAX_VALUE)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 332, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(feedbackTabs, javax.swing.GroupLayout.DEFAULT_SIZE, 192, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 476, Short.MAX_VALUE)
            .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void sendFeedbackButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sendFeedbackButtonActionPerformed

        if(feedbackField.getText().isEmpty())
            return;
        
        HashMap vars = initVars();
        vars.put("feedback", feedbackField.getText());
        final HTTPRequest req = new HTTPRequest(Dogy.WEB_CONTROL_URL+"/leaveFeedback.php");
        req.setVars(vars);
        try {
            req.sendRequest(new Loadable() {

                @Override
                public Object load() {
                    return null;
                }

                @Override
                public Object cancel() {
                    throw new UnsupportedOperationException("Not supported yet.");
                }

                @Override
                public void done(Object done)
                {
                    if(req.getResponse().equals("ok"))
                    {
                        feedbackSendProgress.setVisible(false);
                        feedbackField.setText("");
                    }else
                    {
                        JOptionPane.showMessageDialog(null, "Error "+req.getResponse());
                    }
                }

                @Override
                public void progress(int p) {
                    showFeebackSending(p);
                }
            });
        } catch (MalformedURLException ex) {
            Logger.getLogger(LeaveFeedback.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(LeaveFeedback.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_sendFeedbackButtonActionPerformed

    private void feedbackTabsStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_feedbackTabsStateChanged
        switch(feedbackTabs.getSelectedIndex())
        {
            case LeaveFeedback.PLANNED_TAB:
                getTask(plansPane, TaskStatus.PLANNED, new Loadable()
                              {
                                @Override
                                public Object load()
                                {
                                    return null;
                                }
                                @Override
                                public Object cancel() {
                                    return null;
                                }
                                @Override
                                public void done(Object done)
                                {
                                    if(feedbackTabs.getSelectedIndex() != LeaveFeedback.PLANNED_TAB)
                                          return;
                                    HTTPRequest req = (HTTPRequest)done;
                                    if (!req.getResponse().equals("error") )
                                    {
                                          showTasks(req.getResponse());
                                    }
                                    plansPane.setViewportView(tasksPanel);
                                    plansPane.getVerticalScrollBar().setValue(0);
                                }
                                @Override
                                public void progress(int p)
                                {
                                    progressBar.setValue(p);
                                }
                            });
                break;
            case LeaveFeedback.DONE_TAB:
                getTask( donePane, TaskStatus.DONE, new Loadable()
                              {
                                @Override
                                public Object load()
                                {
                                    return null;
                                }
                                @Override
                                public Object cancel() {
                                    return null;
                                }
                                @Override
                                public void done(Object done)
                                {
                                    if(feedbackTabs.getSelectedIndex() != LeaveFeedback.DONE_TAB)
                                          return;
                                    HTTPRequest req = (HTTPRequest)done;
                                    if (!req.getResponse().equals("error") )
                                    {
                                        showTasks(req.getResponse());
                                    }
                                    donePane.setViewportView(tasksPanel);
                                    donePane.getVerticalScrollBar().setValue(0);
                                }
                                @Override
                                public void progress(int p)
                                {
                                    progressBar.setValue(p);
                                }
                            });
                break;
            case LeaveFeedback.FEEDBACK_TAB:
                getFeedback( feedbackPane, new Loadable()
                              {
                                @Override
                                public Object load()
                                {
                                    return null;
                                }
                                @Override
                                public Object cancel() {
                                    return null;
                                }
                                @Override
                                public void done(Object done)
                                {
                                    if(feedbackTabs.getSelectedIndex() != LeaveFeedback.FEEDBACK_TAB)
                                          return;
                                    HTTPRequest req = (HTTPRequest)done;
                                    if (!req.getResponse().equals("error") )
                                    {
                                        showFeedback(req.getResponse());
                                    }
                                    feedbackPane.setViewportView(tasksPanel);
                                    feedbackPane.getVerticalScrollBar().setValue(0);
                                    
                                }
                                @Override
                                public void progress(int p)
                                {
                                    progressBar.setValue(p);
                                    progressBar.setString("Загрузка... "+p);
                                }
                            });
                break;
        }
}//GEN-LAST:event_feedbackTabsStateChanged

    private void closeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_closeButtonActionPerformed
        this.dispose();
    }//GEN-LAST:event_closeButtonActionPerformed


    private void getFeedback(JScrollPane scrollPane, Loadable load)
    {
        HashMap vars = initVars();
        final HTTPRequest req = new HTTPRequest(Dogy.WEB_CONTROL_URL+"/getFeedback.php");
        req.setVars(vars);

        tasksPanel = new JPanel();
        tasksPanel.setLayout(new BoxLayout(tasksPanel, BoxLayout.PAGE_AXIS));
        scrollPane.add(tasksPanel);
        showTasksLoading(scrollPane);
        scrollPane.setViewportView(progressBar);
        scrollPane.getVerticalScrollBar().setUnitIncrement(10);

        try {
            req.sendRequest(load);
        } catch (MalformedURLException ex) {
            Logger.getLogger(LeaveFeedback.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(LeaveFeedback.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    private void getTask(JScrollPane scrollPane, TaskStatus status, Loadable load)
    {
        HashMap vars = initVars();
        vars.put("type", status);
        final HTTPRequest req = new HTTPRequest(Dogy.WEB_CONTROL_URL+"/tasks.php");
        req.setVars(vars);

        tasksPanel = new JPanel();
        tasksPanel.setLayout(new BoxLayout(tasksPanel, BoxLayout.PAGE_AXIS));
        scrollPane.add(tasksPanel);
        showTasksLoading(scrollPane);
        scrollPane.setViewportView(progressBar);
        scrollPane.getVerticalScrollBar().setUnitIncrement(10);
        scrollPane.getVerticalScrollBar().setValue(0);
        
        try {
            req.sendRequest(load);
        } catch (MalformedURLException ex) {
            Logger.getLogger(LeaveFeedback.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(LeaveFeedback.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void showFeedback(String data)
    {
        tasksPanel.removeAll();
        System.out.println(data);
        if(data.isEmpty())
        {
            JLabel taskLabel = new javax.swing.JLabel();
            taskLabel.setFont(new java.awt.Font("Tahoma", 1, 14)); //
            taskLabel.setText("Пока нет ни одного отзыва... \n");
            tasksPanel.add(taskLabel);
        }else
        {
            String [] tasks = data.split("&");
            for(int t=0; t< tasks.length; t++)
            {
                String [] task = tasks[t].split(":");
                JEditorPane taskLabel = new JEditorPane();
                taskLabel.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
                taskLabel.setText(task[0] + "\n\n" +"Status: " +getTaskDescr(Integer.parseInt(task[3])));
                taskLabel.setBorder(javax.swing.BorderFactory.createTitledBorder(null, task[1] +" "+task[2] + "v " +task[4],
                                    javax.swing.border.TitledBorder.RIGHT,
                                    javax.swing.border.TitledBorder.BOTTOM,
                                    new java.awt.Font("Tahoma", 1, 11),
                                    new java.awt.Color(0, 51, 153))); // NOI18N
                taskLabel.setMaximumSize(new Dimension(65553,65553));
                taskLabel.setEditable(false);
                tasksPanel.add(taskLabel);
            }
        }
        tasksPanel.validate();
        tasksPanel.repaint();
    }
    private void showTasks(String data)
    {
        tasksPanel.removeAll();
        if(data.isEmpty())
        {
            JLabel taskLabel = new javax.swing.JLabel();
            taskLabel.setFont(new java.awt.Font("Tahoma", 1, 14)); //
            taskLabel.setText("Пока нового ничего нет... \n");
            System.out.println("R: ");
            tasksPanel.add(taskLabel);
        }else
        {
            String [] tasks = data.split("&");
            String prevVersion = "";
            JPanel taskPanel = new JPanel();
            for(int t=0; t< tasks.length; t++)
            {
                String [] task = tasks[t].split(":");
                if(!prevVersion.equals(task[1]))
                {
                    //taskPanel.validate();
                    taskPanel = new JPanel();
                    taskPanel.setLayout(new BoxLayout(taskPanel, BoxLayout.PAGE_AXIS));
                    taskPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Version "+task[1],
                                        javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION,
                                        javax.swing.border.TitledBorder.DEFAULT_POSITION,
                                        new java.awt.Font("Tahoma", 1, 11), new java.awt.Color(0, 51, 153)));
                    tasksPanel.add(taskPanel);
                }
                JLabel taskLabel = new JLabel();
                taskLabel.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
                taskLabel.setText("<html>"+task[0] + "<br><i>" +"<font size=2>Status: " +getTaskDescr(Integer.parseInt(task[2]))+"</i></font><br>---");
                taskPanel.setMaximumSize(new Dimension(65553,65553));
                taskPanel.add(taskLabel);
                prevVersion = task[1];
            }
        }
        tasksPanel.validate();
        tasksPanel.repaint();
    }
 
    private void showTasksLoading(JScrollPane jpane)
    {
        progressBar = new JProgressBar();
        progressBar.setFont(new java.awt.Font("Tahoma", 1, 11));
        progressBar.setStringPainted(true);
        progressBar.setString("Загрузка...");
        progressBar.setVisible(true);
        jpane.add(progressBar);
    }
    private void showFeebackSending(int perc)
    {
        if(!feedbackSendProgress.isVisible())
            feedbackSendProgress.setVisible(true);
        feedbackSendProgress.setValue( perc);
        feedbackSendProgress.setString("Посылаю... "+perc);
    }
    
    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new LeaveFeedback().setVisible(true);
            }
        });
    }


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton closeButton;
    private javax.swing.JScrollPane donePane;
    private javax.swing.JTextArea feedbackField;
    private javax.swing.JScrollPane feedbackPane;
    private javax.swing.JProgressBar feedbackSendProgress;
    private javax.swing.JTabbedPane feedbackTabs;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JScrollPane plansPane;
    private javax.swing.JProgressBar progressBar;
    private javax.swing.JButton sendFeedbackButton;
    // End of variables declaration//GEN-END:variables

}
